package com.itmk.web.websocket.controller;

import com.itmk.utils.JWTUtils;
import com.itmk.utils.Result;
import com.itmk.web.userInfo.entity.TokenUUID;
import com.itmk.web.websocket.pojo.Message;
import com.itmk.web.websocket.service.WsService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Controller
@RequestMapping("/ws")
public class WsController {

    @Autowired
    private WsService wsService;
    @RequestMapping("/addMessage")
    @ResponseBody
    public Result addMessage(HttpServletRequest request, @RequestBody Message message){
        //解析唯一标识符
        String token = request.getHeader("Authorization");
        JwtParser jwtParser = Jwts.parser();
        String sign = JWTUtils.getSign();
        Jws<Claims> jwt = jwtParser.setSigningKey(sign).parseClaimsJws(token);
        Claims claims = jwt.getBody();
        String uuid = claims.get("uuid").toString();

        TokenUUID isUUID = wsService.getTokenUUID(uuid);
        if(isUUID==null){
            return Result.error("登录过期，请重新登录");
        }

        boolean res = wsService.addMessage(message,uuid);
        if(res){
            return Result.ok("成功添加消息");
        }
        return Result.error("添加消息失败");
    }

    /**
     * 检索一对一的消息
     * @return
     */
    @RequestMapping("/MessageOneByOne")
    @ResponseBody
    public Result MessageOneByOne(HttpServletRequest request,String touser_uuid){

        //解析唯一标识符
        String token = request.getHeader("Authorization");
        JwtParser jwtParser = Jwts.parser();
        String sign = JWTUtils.getSign();
        Jws<Claims> jwt = jwtParser.setSigningKey(sign).parseClaimsJws(token);
        Claims claims = jwt.getBody();
        String uuid = claims.get("uuid").toString();

        //检索用户收到发出给所有消息
         List<Message> list = wsService.getMessage(uuid,touser_uuid);
        return Result.ok().put("data",list);
    }
}

